using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Text.RegularExpressions;

namespace Skywave.Windows.Forms
{
    public partial class SqlSort : UserControl
    {
        public event EventHandler SortChanged;
        public SqlSort()
        {
            InitializeComponent();
            columns.Add("None", mNoneText);
            AddDropDownItem("None", toolStrip1.Items[0] as ToolStripDropDownButton);
            toolStrip1.Items[1].Click += new EventHandler(tsb1_Click);
        }

        private string mNoneText = "None";
        public string NoneText
        {
            get { return mNoneText; }
            set
            {
                mNoneText = value;
                itemEmpty.Text = mNoneText;
                if (columns.ContainsKey("None")) columns["None"] = mNoneText;
            }
        }

        private Dictionary<string, string> columns = new Dictionary<string, string>();
        private List<string> selectedColumns = new List<string>();
        private bool updateItems = true;
        public void AddColumn(string columnName, string columnCaption)
        {
            if (!columns.ContainsKey(columnName))
            {
                columns.Add(columnName, columnCaption);
                if (updateItems) Refresh_DropDownButtons_DropDownItems();
            }
        }

        public void AddColumn(DataColumn col)
        {
            AddColumn(col.ColumnName, col.Caption);
        }

        public void AddColumn(DataTable dt)
        {
            updateItems = false;
            foreach (DataColumn col1 in dt.Columns)
            {
                AddColumn(col1);
            }
            updateItems = true;
            Refresh_DropDownButtons_DropDownItems();
        }

        public void RemoveColumn(string columnName)
        {
            RemoveSortItem(columnName);
            if (columns.ContainsKey(columnName))
            {
                columns.Remove(columnName);
                if (updateItems) Refresh_DropDownButtons_DropDownItems();
            }
        }

        public void RemoveColumn(DataColumn col)
        {
            RemoveColumn(col.ColumnName);
        }

        public void RemoveColumn(DataTable dt)
        {
            updateItems = false;
            foreach (DataColumn col1 in dt.Columns)
            {
                RemoveColumn(col1);
            }
            updateItems = true;
            Refresh_DropDownButtons_DropDownItems();
        }

        public void ClearColumns()
        {
            columns.Clear();
            columns.Add("None", mNoneText);
            if (updateItems) Refresh_DropDownButtons_DropDownItems();
        }

        private void Refresh_DropDownButtons_DropDownItems()
        {
            List<string> existColumns;
            ArrayList shouldRemoveItems;
            ToolStripDropDownButton ddb1;
            foreach (ToolStripItem tsi1 in toolStrip1.Items)
            {
                if (tsi1 is ToolStripDropDownButton)
                {
                    ddb1 = tsi1 as ToolStripDropDownButton;
                    existColumns = new List<string>();
                    shouldRemoveItems = new ArrayList();
                    foreach (ToolStripItem item1 in ddb1.DropDownItems)
                    {
                        if (selectedColumns.Contains(item1.Tag as string) || !columns.ContainsKey(item1.Tag as string))
                        {
                            shouldRemoveItems.Add(item1);
                        }
                        else if (columns.ContainsKey(item1.Tag as string))
                        {
                            existColumns.Add(item1.Tag as string);
                        }
                    }
                    foreach (ToolStripItem item1 in shouldRemoveItems)
                    {
                        ddb1.DropDownItems.Remove(item1);
                    }
                    foreach (string key in columns.Keys)
                    {
                        if (!existColumns.Contains(key) && !selectedColumns.Contains(key))
                        {
                            AddDropDownItem(key, ddb1);
                        }
                    }
                }
            }
        }

        private void AddDropDownItem(string key, ToolStripDropDownButton ddb1)
        {
            ToolStripItem newItem;
            newItem = ddb1.DropDownItems.Add(columns[key]);
            newItem.Tag = key;
            newItem.Click += new EventHandler(newItem_Click);
        }

        private void RemoveSortItem(string key)
        {
            ToolStripDropDownButton ddb1;
            ToolStripDropDownButton targetDDB = null;
            ToolStripSeparator tss1;
            ToolStripButton tsb1;
            int int1;

            foreach (ToolStripItem tsi1 in toolStrip1.Items)
            {
                if (tsi1 is ToolStripDropDownButton)
                {
                    ddb1 = tsi1 as ToolStripDropDownButton;
                    if (ddb1.Tag as string == key)
                    {
                        targetDDB = ddb1;
                        break;
                    }
                }
            }
            if (targetDDB != null)
            {
                if (toolStrip1.Items.Count != 2) //Empty of SortItem
                {
                    if (selectedColumns.Contains(key)) selectedColumns.Remove(key);
                    int1 = toolStrip1.Items.IndexOf(targetDDB);

                    tss1 = (int1 != 0) ? toolStrip1.Items[int1 - 1] as ToolStripSeparator : toolStrip1.Items[int1 + 2] as ToolStripSeparator;
                    tsb1 = toolStrip1.Items[int1 + 1] as ToolStripButton;
                    toolStrip1.Items.Remove(targetDDB);
                    if (tss1 != null)
                        toolStrip1.Items.Remove(tss1);
                    toolStrip1.Items.Remove(tsb1);
                }
                //else
                //{
                //    targetDDB.Tag = "None";
                //    targetDDB.Text = mNoneText;
                //}
                if (updateItems) Refresh_DropDownButtons_DropDownItems();
            }
        }

        void newItem_Click(object sender, EventArgs e)
        {
            ToolStripItem itemSender = sender as ToolStripItem;
            ToolStripDropDownButton ddb1 = itemSender.OwnerItem as ToolStripDropDownButton;//(itemSender.Container as ToolStripDropDown).OwnerItem;
            //ToolStripSeparator tss1;
            ToolStripButton tsb1;
            //int int1;

            string parentKey = ddb1.Tag as string;
            string key = itemSender.Tag as string;
            if (key == "None")
            {
                if (parentKey != key)
                {
                    RemoveSortItem(parentKey);
                    //if (toolStrip1.Items.Count != 2)
                    //{
                    //    if (selectedColumns.Contains(parentKey)) selectedColumns.Remove(parentKey);
                    //    int1 = toolStrip1.Items.IndexOf(ddb1);

                    //    tss1 = (int1 != 0) ? toolStrip1.Items[int1 - 1] as ToolStripSeparator : toolStrip1.Items[int1 + 2] as ToolStripSeparator;
                    //    tsb1 = toolStrip1.Items[int1 + 1] as ToolStripButton;
                    //    toolStrip1.Items.Remove(ddb1);
                    //    if (tss1 != null)
                    //        toolStrip1.Items.Remove(tss1);
                    //    toolStrip1.Items.Remove(tsb1);
                    //}
                }
            }
            else if (!selectedColumns.Contains(key))
            {
                if (selectedColumns.Contains(parentKey)) selectedColumns.Remove(parentKey);
                ddb1.Tag = key;
                ddb1.Text = itemSender.Text;
                selectedColumns.Add(key);
                if (toolStrip1.Items.IndexOf(ddb1) == toolStrip1.Items.Count - 1 - 1)
                {
                    ToolStripDropDownButton newDDB = new ToolStripDropDownButton(mNoneText);
                    newDDB.Tag = "None";
                    AddDropDownItem("None", newDDB);
                    toolStrip1.Items.Add(new ToolStripSeparator());
                    toolStrip1.Items.Add(newDDB);
                    tsb1 = new ToolStripButton(imageListSort.Images[0]);
                    tsb1.Tag = " ASC";
                    tsb1.ToolTipText = "";
                    tsb1.ImageTransparentColor = Color.Magenta;
                    tsb1.Click += new EventHandler(tsb1_Click);
                    toolStrip1.Items.Add(tsb1);
                }
                Refresh_DropDownButtons_DropDownItems();
            }
            if (SortChanged != null) SortChanged(this, new EventArgs());
        }

        void tsb1_Click(object sender, EventArgs e)
        {
            ToolStripButton tsb1 = sender as ToolStripButton;
            if (tsb1.Tag as string == " ASC")
            {
                tsb1.Tag = " DESC";
                tsb1.Image = imageListSort.Images[1];
            }
            else
            {
                tsb1.Tag = " ASC";
                tsb1.Image = imageListSort.Images[0];
            }
            if (SortChanged != null) SortChanged(this, new EventArgs());
        }

        public string GetSqlSortString()
        {
            string key;
            string resault = " ORDER BY ";
            ToolStripDropDownButton tsd1;
            ToolStripButton tsb1;
            ToolStripItem tsi1;
            for (int i = 0; i < toolStrip1.Items.Count; i++)
            {
                tsi1 = toolStrip1.Items[i];
                if (tsi1 is ToolStripDropDownButton)
                {
                    tsd1 = tsi1 as ToolStripDropDownButton;
                    key = tsd1.Tag as string;
                    if (key == "None") break;
                    resault += key;
                }
                else if (tsi1 is ToolStripButton)
                {
                    tsb1 = tsi1 as ToolStripButton;
                    key = tsb1.Tag as string;
                    resault += key + ", ";
                }
            }
            if (resault.EndsWith(", "))
                resault = resault.Remove(resault.Length - 2, 2);
            else
                resault = "";
            return resault;
        }

        public string GetSortColumns()
        {
            string key;
            string resault = "";
            ToolStripDropDownButton tsd1;
            ToolStripButton tsb1;
            ToolStripItem tsi1;
            for (int i = 0; i < toolStrip1.Items.Count; i++)
            {
                tsi1 = toolStrip1.Items[i];
                if (tsi1 is ToolStripDropDownButton)
                {
                    tsd1 = tsi1 as ToolStripDropDownButton;
                    key = tsd1.Tag as string;
                    if (key == "None") break;
                    resault += key;
                }
                else if (tsi1 is ToolStripButton)
                {
                    tsb1 = tsi1 as ToolStripButton;
                    key = tsb1.Tag as string;
                    resault += key + ",";
                }
            }
            if (resault.EndsWith(","))
                resault = resault.Remove(resault.Length - 1, 1);
            else
                resault = "";
            return resault;
        }
        public void SetSortColumns(string sortCols)
        {
            if (sortCols == null) sortCols = "";
            ToolStripButton tsb1;
            ToolStripDropDownButton newDDB;
            selectedColumns.Clear();
            toolStrip1.Items.Clear();
            string colName, sortType;
            Regex re = new Regex(@"(?<G1>[^,]*)\s(?<G2>[^,]*)");
            if (re.IsMatch(sortCols))
            {
                foreach (Match m in re.Matches(sortCols))
                {
                    colName = m.Groups["G1"].Value;
                    sortType = m.Groups["G2"].Value;
                    if (columns.ContainsKey(colName))
                    {
                        if (toolStrip1.Items.Count != 0)
                            toolStrip1.Items.Add(new ToolStripSeparator());
                        newDDB = new ToolStripDropDownButton(columns[colName]);
                        newDDB.Tag = colName;
                        AddDropDownItem("None", newDDB);
                        toolStrip1.Items.Add(newDDB);
                        tsb1 = new ToolStripButton(imageListSort.Images[(sortType == "ASC") ? 0 : 1]);
                        tsb1.Tag = " " + sortType;
                        tsb1.ToolTipText = "";
                        tsb1.ImageTransparentColor = Color.Magenta;
                        tsb1.Click += new EventHandler(tsb1_Click);
                        toolStrip1.Items.Add(tsb1);
                        selectedColumns.Add(colName);
                    }
                }
            }
            if (toolStrip1.Items.Count != 0)
                toolStrip1.Items.Add(new ToolStripSeparator());
            newDDB = new ToolStripDropDownButton(mNoneText);
            newDDB.Tag = "None";
            AddDropDownItem("None", newDDB);
            toolStrip1.Items.Add(newDDB);
            tsb1 = new ToolStripButton(imageListSort.Images[0]);
            tsb1.Tag = " ASC";
            tsb1.ToolTipText = "";
            tsb1.ImageTransparentColor = Color.Magenta;
            tsb1.Click += new EventHandler(tsb1_Click);
            toolStrip1.Items.Add(tsb1);
            Refresh_DropDownButtons_DropDownItems();
        }

        public Dictionary<string, string> GetSortColumnsDictionary()
        {
            Dictionary<string, string> r = new Dictionary<string, string>();
            string key, preKey = "";
            ToolStripDropDownButton tsd1;
            ToolStripButton tsb1;
            ToolStripItem tsi1;
            for (int i = 0; i < toolStrip1.Items.Count; i++)
            {
                tsi1 = toolStrip1.Items[i];
                if (tsi1 is ToolStripDropDownButton)
                {
                    tsd1 = tsi1 as ToolStripDropDownButton;
                    key = tsd1.Tag as string;
                    if (key == "None") break;
                    preKey = key;
                }
                else if (tsi1 is ToolStripButton)
                {
                    tsb1 = tsi1 as ToolStripButton;
                    key = tsb1.Tag as string;
                    if (preKey != "")
                        r.Add(preKey.Trim(), key.Trim());
                    preKey = "";
                }
            }
            return r;
        }
    }
}